package com.cykj.v_m_sprintboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.cykj.v_m_sprintboot.bean.PageInf;
import com.cykj.v_m_sprintboot.bean.TbCommorityCategory;
import com.cykj.v_m_sprintboot.bean.TbVmi;
import com.cykj.v_m_sprintboot.service.TbCommodityService;
import com.cykj.v_m_sprintboot.service.TbVmiService;
import com.cykj.v_m_sprintboot.tool.GetTime;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import  java.beans.Introspector;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class VMController {
    @Autowired
    public TbCommodityService tbCommodityService;

    //生成订单号方法
    public static String getOrderId() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<6;i++){
            result+=random.nextInt(10);
        }
        return newDate+result;
    }

    //查询售货机
    @RequestMapping("/vmiInfo")
    public Map<String, Object> vmiInfo(){//前端商品
        Map<String,Object> qdCommMap = new HashMap<>();
        Map<String,Object> qmap = new HashMap<>();

        List<TbVmi> vmiList = tbCommodityService.vmiInfo();
        for (int i=0;i<vmiList.size();i++){
            System.out.println(vmiList.get(i)+"-----0910");
        }
        qmap.put("vmiList",vmiList);
        return qmap;
    }


    //售货机端支付成功后，售货机出货，从数据库减少相应商品数量
    @RequestMapping("vmOut")
    @ResponseBody
    public Map<String, Object> vmPay(@RequestBody String datalist){
        JSONObject jsonObject = JSONObject.parseObject(datalist); //转为JSON 格式
        System.out.println(jsonObject+"微信小程序正在调用。。。");
        String count = jsonObject.getString("count"); // 取值
        String money = jsonObject.getString("money");
        String dlist = jsonObject.getString("datalist");
        String tradeNo = jsonObject.getString("outTradeNo");//订单号
        List<Map> dishslist = JSONObject.parseArray(dlist, Map.class);
        System.out.println(count+"+"+money+"\n"+dlist+"\n"+dishslist);
        for( int i = 0; i < dishslist.size(); i++ ) {
            String conName = dishslist.get(i).get("comName").toString();//商品名
            String goodsType = "饮料";//商品种类
            String goodsUnit = "瓶";//商品单位
            String orderTime = GetTime.getTime();
            String comPrice = dishslist.get(i).get("comPrice").toString();//商品单价
            String comImage = dishslist.get(i).get("comImage").toString();//商品图片地址
            String categoryID = dishslist.get(i).get("categoryID").toString();//商品id
            String conNum = dishslist.get(i).get("conNum").toString();//商品数
            String vmid = dishslist.get(i).get("vmid").toString();//售货机id
            System.out.println(conName+conNum+vmid);
            tbCommodityService.vmPay(conName,goodsType,goodsUnit,categoryID,conNum,orderTime,vmid);
            tbCommodityService.vmFundComm(comImage,conName,conNum,comPrice,tradeNo);
        }
        //添加至订单表
        String fundName = jsonObject.getString("name");//支付名字
        String fundState = "已支付";//支付状态
        String fundTime = jsonObject.getString("time");//支付时间
        String fundMoney = jsonObject.getString("money");//支付金额
        String fundNum = jsonObject.getString("count");//购买数量
        String payMethod = jsonObject.getString("支付宝");//支付方式
        String VMID = jsonObject.getString("VM");//售货机ID
        String openID = jsonObject.getString("openID");//openID
        tbCommodityService.vmOrder(tradeNo,fundName,fundTime,fundState,fundMoney,fundNum,payMethod,VMID,openID);
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> list = new ArrayList<String>();
        list.add("success");
        list.add("out");
        map.put("list",list);
        System.out.println("微信小程序调用完成。。。");
        return map;
    }


    //配送员在售货机端补货后，向数据库添加数据
    @RequestMapping("vmSup")
    @ResponseBody
    public Map<String, Object> vmSup(@RequestBody String data){
        System.out.println(data);
        JSONObject jsonObject = JSONObject.parseObject(data); //转为JSON 格式
        System.out.println(jsonObject+"微信小程序正在调用。。。");
        //去减少商品表的商品数量
        String dlist = jsonObject.getString("datalist");
        System.out.println(dlist);
        List<Map> dishslist = JSONObject.parseArray(dlist, Map.class);
        System.out.println(dishslist);
        for( int i = 0; i < dishslist.size(); i++ ) {
            String conName = dishslist.get(i).get("comName").toString();//商品名
            String conNum = dishslist.get(i).get("conNum").toString();//商品数
            String vmid = dishslist.get(i).get("vmid").toString();//售货机id
            System.out.println(conName+conNum);
            tbCommodityService.vmSup(conName,conNum,vmid);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> list = new ArrayList<String>();
        list.add("success");
        list.add("add");
        map.put("list",list);
        System.out.println("微信小程序调用完成。。。");
        return map;
    }
    
    //小程序发起支付请求
    @RequestMapping("vmPay")
    @ResponseBody
    public  AlipayTradePrecreateResponse VMPay(@RequestBody String data){
        System.out.println(data);
        JSONObject jsonObject = JSONObject.parseObject(data); //转为JSON 格式
        String dlist = jsonObject.getString("datalist");
        String money = jsonObject.getString("money");
        System.out.println(dlist);
        String orderId = getOrderId();
        System.out.println(orderId);
//        List<Map> dishslist = JSONObject.parseArray(dlist, Map.class);
//        System.out.println(dishslist);
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2021000118625726",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCGEiTnrYJ6wOG3vUZcOzeC8s4Y3BO6hq74gwUa2uaaTWIYqr94bEcpMqfsj/HPP/qXg1+liaVNLUNWrZ+PJUT3WDBtrJTAirhbgkHWqcVftS7E6C7TIsymKDFMT9APiBHrinHS3rkj55ALrEbPMZC7H9R2o0Qw7YwZ1Kr0xEe3xzszUli9Y/FxpDjQ1wOq7Fm+o9xqBpVdKE1Vdx+DjLzsE0Tr/qhG9Jg5V5aawnZSwFmVVBsX3B3xsHwo7wMMOnf0YA0JXW9EUpUlxfsvsZIL30F1zwvj3cJp4LAHxyRisy3icQLSK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QYdzESdkbHEYKECgYEAhoQ03fqWKwHnszhiUbxDuiqQ9znzGw0r/E90+u5zKBVd07nTsYsZRh/1toWBgV+dsGsb48redJqlrVuMX2tfPzZ0YTdDTuGsVrkEpJke2Vc3BGT/xy7CLd8p+0uDd1ccJnNAEE7zzPnMytYSn6qbn3x9l9STF9ikVSDGUNuIJ9E=",
                "json","GBK",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq8IorGmkb2+h23qG5JXwNr855dOL71h8mGq90G+uCAT/ZDAD7D+zwdFkZrjTpZNpYVnpKhBeHKV8j2KzH+M8Sb7J894PZBejWSsqaRrfkC2l1lQG02/fKL7WfQftsTfoHCKjpgtWfmenZeHBMZc0NnQjmT4g0EsD6sZK3RYoQ5YXFadJd8i6OMwitfYwLC1HRO90yIALoMa6qtXxczi0NGJDaWBafEYEOEI3QG1v5qgijFPK34w78imDiIxdMKehvcalRBXKBJtqK87UUZpSJLlht8buxva715mKa0FP4WF0D/SN0CljtusfyAeluU54d3f1jfWqG9tE6m2yqRvs4QIDAQAB",
                "RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl("");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        bizContent.put("total_amount", money);
        bizContent.put("subject", "测试商品");
        bizContent.put("qr_code_timeout_express", "10m");

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

//// 结算信息，按需传入
//JSONObject settleInfo = new JSONObject();
//JSONArray settleDetailInfos = new JSONArray();
//JSONObject settleDetail = new JSONObject();
//settleDetail.put("trans_in_type", "defaultSettle");
//settleDetail.put("amount", 0.01);
//settleDetailInfos.add(settleDetail);
//settleInfo.put("settle_detail_infos", settleDetailInfos);
//bizContent.put("settle_info", settleInfo);

//// 二级商户信息，按需传入
//JSONObject subMerchant = new JSONObject();
//subMerchant.put("merchant_id", "2088000603999128");
//bizContent.put("sub_merchant", subMerchant);

//// 业务参数信息，按需传入
//JSONObject businessParams = new JSONObject();
//businessParams.put("busi_params_key", "busiParamsValue");
//bizContent.put("business_params", businessParams);

//// 营销信息，按需传入
//JSONObject promoParams = new JSONObject();
//promoParams.put("promo_params_key", "promoParamsValue");
//bizContent.put("promo_params", promoParams);

        request.setBizContent(bizContent.toString());
        System.out.println("+++"+request);
//        AlipayTradePrecreateResponse response = new AlipayTradePrecreateResponse();
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println(response+"调用成功");
        } else {
            System.out.println(response+"调用失败");
        }

        return response;
    }


    @RequestMapping("vmPayTest")
    @ResponseBody
    public  AlipayTradeQueryResponse vmPayTest(@RequestBody String data){
        System.out.println(data);
        JSONObject jsonObject = JSONObject.parseObject(data); //转为JSON 格式
        String outTradeNo = jsonObject.getString("outTradeNo");
        System.out.println(outTradeNo);
//        System.out.println(orderId);
//        List<Map> dishslist = JSONObject.parseArray(dlist, Map.class);
//        System.out.println(dishslist);
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2021000118625726",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCGEiTnrYJ6wOG3vUZcOzeC8s4Y3BO6hq74gwUa2uaaTWIYqr94bEcpMqfsj/HPP/qXg1+liaVNLUNWrZ+PJUT3WDBtrJTAirhbgkHWqcVftS7E6C7TIsymKDFMT9APiBHrinHS3rkj55ALrEbPMZC7H9R2o0Qw7YwZ1Kr0xEe3xzsz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M2ySfSfTM9rHFzc87SYWpjwF3KSARQsNGmoSBFO60EGmI+KQ+mRubMMjlUuWJC770JoFcRjcwBtqjuQ09n04Hwq0RYWK+tL3ggce6k5PwH6YbtdwpC68H6VoWimbXo/pNO8BONSAgF/QvaTQYdzESdkbHEYKECgYEAhoQ03fqWKwHnszhiUbxDuiqQ9znzGw0r/E90+u5zKBVd07nTsYsZRh/1toWBgV+dsGsb48redJqlrVuMX2tfPzZ0YTdDTuGsVrkEpJke2Vc3BGT/xy7CLd8p+0uDd1ccJnNAEE7zzPnMytYSn6qbn3x9l9STF9ikVSDGUNuIJ9E=",
                "json","GBK",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq8IorGmkb2+h23qG5JXwNr855dOL71h8mGq90G+uCAT/ZDAD7D+zwdFkZrjTpZNpYVnpKhBeHKV8j2KzH+M8Sb7J894PZBejWSsqaRrfkC2l1lQG02/fKL7WfQftsTfoHCKjpgtWfmenZeHBMZc0NnQjmT4g0EsD6sZK3RYoQ5YXFadJd8i6OMwitfYwLC1HRO90yIALoMa6qtXxczi0NGJDaWBafEYEOEI3QG1v5qgijFPK34w78imDiIxdMKehvcalRBXKBJtqK87UUZpSJLlht8buxva715mKa0FP4WF0D/SN0CljtusfyAeluU54d3f1jfWqG9tE6m2yqRvs4QIDAQAB",
                "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
//bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response;
    }


}
